﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using SurveyHost.Support;
using Microsoft.Web.Mvc;
using System.Text;
using SurveyHost.Models;

namespace SurveyHost.Controllers
{
    public class ParagraphController : BaseController
    {
        [AcceptVerbs(HttpVerbs.Get), Authorize(Roles = "Admin")]
        public ActionResult Edit(string name)
        {
            Paragraph p = null;
            if (name.IsNullOrEmpty() || (p = Paragraph.Retrieve(name)) == null)
                return ErrorView("Paragraph Error", "An error occurred when attempting to edit a paragraph", "Unable to locate the specified paragraph to edit.", null, null);

            return View("Edit", p);
        }
        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Admin"), ValidateAntiForgeryToken]
        public ActionResult Save(string name, string paragraph)
        {
            Paragraph p = null;
            if (name.IsNullOrEmpty() || paragraph.IsNullOrEmpty() || (p = Paragraph.Retrieve(name)) == null)
                return ErrorView("Paragraph Error", "An error occurred when attempting to edit a paragraph", "Unable to locate the specified paragraph to edit.", null, null);
            if (p.Text != paragraph)
            {
                p.Text = paragraph;
                Paragraph.Update(p);
            }
            return SuccessView("Success", "your paragraph has been saved", "Your paragraph has been successfully saved.", null);
        }

        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Admin")]
        public JsonResult SaveInPlace(string name, string paragraph)
        {
            Paragraph p = null;
            if (name.IsNullOrEmpty() || paragraph.IsNullOrEmpty() || (p = Paragraph.Retrieve(name)) == null)
                return Json("Unable to save changes.  This paragraph will revert to the original value on next load.");
            if (p.Text != paragraph)
            {
                p.Text = paragraph;
                Paragraph.Update(p);
            }
            return Json(paragraph.HtmlEncode());
        }
    }
}
